import threading
import tkinter as tk
from tkinter import filedialog,messagebox
# from spcparser import *
from log import AppLogger
from config import ConfigManager
from watchDir import watcher
import os
import sys
from web import runWerServer
import queue
import gv


class UserForm(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.log =  AppLogger('my_app.log', max_bytes=1024*5000, backup_count=2)
        self.log.info("开始解析配置文件")
        
        self.config = ConfigManager('config.ini')
        paths = self.config.paths()
        
        self.master = master
        self.master.title("User Form")
        self.master.attributes('-topmost', True)

        self.queue = gv.q
        self.pause_event = threading.Event()
        self.pause_event.set() #停止中...
        gv.sample_event.clear()
        gv.compare_event.clear()
        
        self.btn_run= tk.Button(self.master, text="停止中", command=self.pause_worker)
        self.btn_run.pack()
        
        # 初始化文本框控件,并设置文本框有竖直滚动条
        self.text_box = tk.Text(self.master, height=15, width=50, wrap=tk.WORD)  # 设置文本自动换行
        self.scroll_bar = tk.Scrollbar(self.master, command=self.text_box.yview)  # 为滚动条关联文本框的垂直视图
        self.text_box.config(yscrollcommand=self.scroll_bar.set)  # 设置文本框调用滚动条的 set 方法来更新滚动条的位置

        # 布局控件
        self.text_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)  # 让文本框填满可用空间
        self.scroll_bar.pack(side=tk.RIGHT, fill=tk.Y)  # 将滚动条放置在文本框的右边，并填满竖直空间
        
        self.pause_event.set()
        self.pause_worker()
        
        self.after(1000, self.update_msg)
    
    def update_msg(self):
        self.after(1000, self.update_msg)
        # if gv.compare_event.is_set():
        #     msg = "对比样本中.."
        #     self.text_box.insert(tk.END, msg.strip()+"\n")
        #     self.text_box.see(tk.END)
        #     self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部
            
        # if gv.sample_event.is_set():
        #     msg = "增加标准样本中.."
        #     self.text_box.insert(tk.END, msg.strip()+"\n")
        #     self.text_box.see(tk.END)
        #     self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部
        # else:
        #     msg = "常规分析中.."
        #     self.text_box.insert(tk.END, msg.strip()+"\n")
        
        while not self.queue.empty():
            msg = self.queue.get()
            msg=str(msg)
            print(msg)
            if len(self.text_box.get("1.0", "end-1c"))>5000:
                self.text_box.delete(1.0, tk.END)
                self.text_box.see(tk.END)
                self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部
            
            if msg=="clear":
                self.text_box.delete(1.0, tk.END)
                self.text_box.see(tk.END)
                self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部
                continue
            elif msg.startswith('compare:'):
                self.text_box.insert(tk.END, msg[8:].strip()+"\n")
                self.text_box.see(tk.END)
                self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部
            
            elif msg.startswith('sample:'):
                self.text_box.insert(tk.END, msg[7:].strip()+"\n")
                self.text_box.see(tk.END)
                self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部
            else:
                self.text_box.insert(tk.END, msg.strip()+"\n")
                self.text_box.see(tk.END)
                self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部
            # self.text_box.insert(tk.END, msg.strip()+"\n")
            # self.text_box.see(tk.END)
            # self.text_box.yview_moveto(1.0)  # 确保滚动条移动到最底部

    
    def pause_worker(self):
        if self.pause_event.is_set():  # 如果已经暂停，则恢复
            self.pause_event.clear()
            #设置 开始按钮的文字为“运行中...”
            self.btn_run.config(text="运行中...")
        else:
            self.pause_event.set()
            #设置 开始按钮的文字为“停止中...”
            self.btn_run.config(text="停止中...") 
    def watchDir(self):
        paths = self.config.paths()
        self.watcherThread = threading.Thread(target=watcher,args=(paths['spath'],self.queue))
        self.watcherThread.daemon = True
        self.watcherThread.start()
    
    def listenNet(self):
        paths = self.config.paths()
        self.webThread = threading.Thread(target=runWerServer,args=())
        self.webThread.daemon = True
        self.webThread.start()    
        
if __name__ == '__main__':
    if not os.path.exists('config.ini'):
        messagebox.showerror("错误", "配置文件不存在")
        sys.exit()
    config = ConfigManager('config.ini')
    paths = config.paths()
    for key,path in paths.items():
        if not os.path.exists(path):
            messagebox.showerror("错误", "不存在:"+path)
            sys.exit()
    
    app = UserForm(master=tk.Tk())
    
    app.watchDir()
    app.listenNet()
    
    app.mainloop()